package com.exm.collectcodenew.zookeeper;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class SyncLock {
//    private ZooKeeper zk; // 创建一个与服务器的连接
//    void getLock() throws  InterruptedException, IOException, KeeperException {
//        zk = new ZooKeeper("59.110.35.177:2181" ,
//                2000, new Watcher() {
//            // 监控所有被触发的事件
//            public void process(WatchedEvent event) {
//                System.out.println("已经触发了" + event.getType() + "事件！");
//            }
//        });
//        List<String> list = zk.getChildren("root", false);
//        String[] nodes = list.toArray(new String[list.size()]);
//        Arrays.sort(nodes);
//        if(myZnode.equals(root+"/"+nodes[0])){
//            System.out.println("myZnode获取了同步锁");
//        }
//        else{
//            waitForLock(nodes[0]);
//        }
//    }
//    void waitForLock(String lower) throws InterruptedException, KeeperException, IOException {
//        Stat stat = zk.exists(root + "/" + lower,true);
//        if(stat != null){
//            mutex.wait();
//        }
//        else{
//            getLock();
//        }
//    }
}
